<template>
    <div class="addGoods">
        <div class="addGoods_title">基本信息</div>
        <div class="addGoods_form">
            <el-form label-position="right" label-width="100px" :model="formAddGoods">
                <el-form-item label="商品名称">
                    <el-input v-model="formAddGoods.name" size="small" style="width: 320px;"
                        placeholder="请填写商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品简介">
                    <el-input v-model="formAddGoods.description" size="small" style="width: 320px;"
                        placeholder="请填写商品简介"></el-input>
                </el-form-item>
                <el-form-item label="商品大图">
                    <el-upload class="avatar-uploader" :action="action" :data="uploadData" :show-file-list="false"
                        :on-success="handleSuccess" :before-upload="beforeUpload">
                        <img v-if="this.formAddGoods.images" :src="this.formAddGoods.images" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-cascader style="width: 220px;" size="small" v-model="formAddGoods.category_ids"
                        :options="categoryListToOptions(categoryList)" :props="{ expandTrigger: 'hover', multiple: true }"
                        placeholder="请选择商品分类"></el-cascader>
                </el-form-item>
                <!-- <el-form-item label="所属供应商">
                    <el-input v-model="formAddGoods.type" size="small"></el-input>
                </el-form-item> -->
                <el-form-item label="品牌">
                    <el-cascader style="width: 220px;" size="small" v-model="formAddGoods.brand_id" :options="brandList"
                        :props="{ expandTrigger: 'click' }" placeholder="请选择品牌">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="商品介绍">
                    <el-input v-model="formAddGoods.detail" style="width: 320px;" size="small" type="textarea" :rows="4"
                        placeholder="请填写商品介绍"></el-input>
                </el-form-item>
                <el-form-item label="备注说明">
                    <el-input v-model="formAddGoods.remarks" style="width:320px;" size="small" type="textarea" :rows="2"
                        placeholder="请填写备注说明"></el-input>
                </el-form-item>
                <el-form-item label="规格">
                    <el-input v-model="formAddGoods.specs" style="width: 100px;" placeholder="件/个/数"
                        size="small"></el-input>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="formAddGoods.sort" size="small" style="width:100px"></el-input>
                </el-form-item>
                <el-form-item label="售卖金额">
                    <el-input v-model="formAddGoods.price" size="small" style="width:100px">
                        <span slot="prefix" style="color:#000000">￥</span>
                    </el-input>
                </el-form-item>
                <el-form-item label="库存">
                    <el-input v-model="formAddGoods.stock_num" size="small" style="width:100px"></el-input>
                </el-form-item>
                <el-form-item label="上架平台">
                    <div class="formCheckbox">
                        <el-checkbox v-model="platformAll" @change="handlePlatformAllChange">全选</el-checkbox>
                        <el-checkbox-group v-model="formAddGoods.platform" @change="handleCheckedPlatformsChange">
                            <el-checkbox :label="1">前台</el-checkbox>
                            <el-checkbox :label="2">小程序</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <div class="addGoods_Bottom">
            <el-button size="small" @click="dialog_success = true">返回</el-button>
            <el-button type="primary" size="small" @click="confirmAdd">确定</el-button>
        </div>


        <!--添加商品成功跳转页面对话框 -->
        <el-dialog title="提醒" :show-close="false" :visible.sync="dialog_success" width="30%">
            <P style="line-height: 22px;color:black">
                <span v-if="isAdd">是否取消{{ editGoods ? '编辑' : '添加' }}商品并返回商品管理页面</span>
                <span v-else>您已成功{{ editGoods ? '编辑' : '添加' }}商品，即将返回商品管理页面(点击取消则继续{{ editGoods ? '编辑' : '添加' }}商品)</span>
            </P>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialog_success = false" size="small">取 消</el-button>
                <el-button type="primary" @click="toPage('商品管理')" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            editGoods: true,//true编辑商品,false添加商品
            goods_id: 0,//商品id

            dialog_success: false,//添加商品成功跳转页面对话框
            isAdd: true,//对话框内容显示,true显示取消添加商品,false显示成功添加商品
            uploadData: {},//上传图片配置的参数
            action: 'https://guansj.oss-cn-shenzhen.aliyuncs.com',//上传图片action

            brandList: null,//品牌列表
            categoryList: null,//分类列表
            platformAll: false,//上架平台全选
            formAddGoods: {
                name: '商品名称',//商品名称
                description: '商品简介',//商品简介
                images: 'https://guansj.oss-cn-shenzhen.aliyuncs.com/gsj_new/system/202310/25/memberBigIcon_huangjin.png',//图片路径
                category_ids: [[75]],//分类ID
                brand_id: [32],//品牌ID
                detail: '商品介绍',//商品介绍
                remarks: '备注',//备注
                specs: '商品规格',//商品规格
                sort: '1',//排序
                price: '10',//价格
                stock_num: '10',//库存
                platform: [],//上架平台 1前台 2小程序 多个 逗号隔开
                // supplier_id: '',//供应商ID 可不填
            },
            verifyMessage: '',//表单验证信息字段
        }
    },
    created() {
        this.getCategory()
        if (this.$route.params.id) {//不是编辑，没有传id则是新增商品
            this.goods_id = this.$route.params.id
            this.editGoods = true
            this.getGoodsDetail()
        } else {
            this.editGoods = false
            this.goods_id = 0
        }
    },
    methods: {

        // 获取商品详情
        getGoodsDetail() {
            let data = {
                goods_id: this.goods_id,
            }
            this.my_request('supplier/market/goods/detail', data).then(res => {
                console.log(res, '获取商品详情');
                let { code, data } = res.data
                if (200 == code) {
                    this.formAddGoods.name = data.name
                    this.formAddGoods.description = data.description
                    this.formAddGoods.images = data.images
                    this.formAddGoods.brand_id = [data.brand_id]
                    this.formAddGoods.detail = data.detail
                    this.formAddGoods.specs = data.specs
                    this.formAddGoods.sort = data.sort
                    this.formAddGoods.price = data.price
                    this.formAddGoods.stock_num = data.stock_num
                    this.formAddGoods.remarks = data.remarks
                    this.formAddGoods.platform = data.platform
                    this.handleCheckedPlatformsChange(this.formAddGoods.platform)

                    // 商品分类
                    data.category_ids = data.category_ids.split(',')
                    this.formAddGoods.category_ids = []
                    data.category_ids.map(id => {
                        this.categoryList && this.categoryList.map(item => {
                            if (item.id == id) {
                                this.formAddGoods.category_ids.push([id])
                            } else {
                                item.child.map(childItem => {
                                    if (childItem.id == id && childItem.parent_id != 0) {
                                        this.formAddGoods.category_ids.push([childItem.parent_id, id])
                                    }
                                });
                            }
                        })
                    })
                }
            })
        },

        // 确定添加/编辑 商品
        confirmAdd() {
            console.log(this.formAddGoods, '确定添加商品');
            // 表单验证
            if (!this.verify()) {
                this.$message({
                    message: this.verifyMessage,
                    type: 'error',
                });
                return
            }
            let data = {
                hotel_id: sessionStorage.getItem('hotel_id'),//当前酒店id
                ...this.formAddGoods
            }
            data.platform = data.platform.join(',')
            data.brand_id = data.brand_id[0]
            data.category_ids = data.category_ids.length && data.category_ids.map(item => {
                let id = item[item.length - 1]
                return id
            }).join(',')
            console.log(this.formAddGoods, '确定添加商品', data);


            let action = '添加'
            let method = "POST"
            if (this.editGoods) {
                data.goods_id = this.goods_id
                action = '编辑'
                method = "PUT"
            }

            this.my_request('supplier/market/goods', data, method).then(res => {
                console.log(res, '确定添加商品res');
                let { code } = res.data
                if (200 === code) {
                    this.$message({
                        message: `${action}成功`,
                        type: 'success',
                        duration: 1500,
                    });
                    if (!this.editGoods) {
                        this.clearData()
                    }
                    setTimeout(() => {
                        this.dialog_success = true
                    }, 1600)
                } else {
                    this.$message({
                        message: `${action}失败,请重试`,
                        type: 'error',
                        duration: 1500,
                    });
                }
            })
        },

        // 表单验证
        verify() {
            let isVerify = false
            if (this.formAddGoods.name == '') {
                isVerify = false
                this.verifyMessage = '请填写商品名称'
            } else if (this.formAddGoods.description == '') {
                isVerify = false
                this.verifyMessage = '请填写商品简介'
            } else if (this.formAddGoods.images == '') {
                isVerify = false
                this.verifyMessage = '请上传商品图片'
            } else if (this.formAddGoods.category_ids == '') {
                isVerify = false
                this.verifyMessage = '请选择商品分类'
            } else if (this.formAddGoods.brand_id == '') {
                isVerify = false
                this.verifyMessage = '请选择品牌'
            } else if (this.formAddGoods.detail == '') {
                isVerify = false
                this.verifyMessage = '请填写商品介绍'
            } else if (this.formAddGoods.remarks == '') {
                isVerify = false
                this.verifyMessage = '请填写备注说明'
            } else if (this.formAddGoods.specs == '') {
                isVerify = false
                this.verifyMessage = '请填写商品规格'
            } else if (this.formAddGoods.sort == '') {
                isVerify = false
                this.verifyMessage = '请填写商品排序'
            } else if (this.formAddGoods.price == '') {
                isVerify = false
                this.verifyMessage = '请填写商品售卖金额'
            } else if (this.formAddGoods.stock_num == '') {
                isVerify = false
                this.verifyMessage = '请填写商品库存'
            } else if (this.formAddGoods.platform.length == 0) {
                isVerify = false
                this.verifyMessage = '请选择上架平台'
            } else {
                isVerify = true
            }
            console.log(isVerify, 'isVerifyisVerifyisVerifyisVerify');
            return isVerify

        },


        /**
        * 
        * @param {*} pageName 页面名 
        */
        toPage(pageName) {
            this.dialog_success = false
            if (pageName == '商品管理') {
                setTimeout(() => {
                    this.$router.replace('/Supermarket/GoodsManagement')
                }, 300)
            }
        },
        // 处理数据
        clearData() {
            // 处理数据
            this.formAddGoods = {
                name: '',//商品名称
                description: '',//商品简介
                images: '',//图片路径
                category_ids: [],//分类ID
                brand_id: [],//品牌ID
                detail: '',//商品介绍
                remarks: '',//备注
                specs: '',//商品规格
                sort: '',//排序
                price: '',//价格
                stock_num: '',//库存
                platform: [],//上架平台 1前台 2小程序 多个 逗号隔开
            }
            this.platformAll = false
        },
        // 图片上传之前的钩子
        beforeUpload(file) {
            console.log(file.name, 'fileuploadData');
            // 发送请求获取上传配置参数
            return this.my_request('https://newapi.guansj.com/api/common/oss-upload-init')
                .then(res => {
                    // 根据返回的配置参数进行逻辑处理（例如设置请求头、参数等）
                    // console.log('图片上传之前的钩子', res);
                    let { code, data } = res.data
                    if (200 == code) {
                        this.uploadData = {
                            OSSAccessKeyId: data.accessid,
                            policy: data.policy,
                            Signature: data.signature,
                            key: `${data.dir}${file.name}`,
                            success_action_status: 200,
                        }
                    }
                    // 继续执行上传操作
                    return true;
                })
                .catch(error => {
                    console.error('图片上传之前的钩子请求失败', error);
                    // 取消上传
                    return false;
                });
        },
        // 上传成功的钩子
        handleSuccess() {//设置图片url
            this.formAddGoods.images = `${this.action}/${this.uploadData.key}`;
        },


        // 全选上架平台多选按钮
        handlePlatformAllChange(val) {
            console.log(this.formAddGoods.platform,val,'this.formAddGoods.platform');
            this.formAddGoods.platform = val ? [1, 2] : [];
        },
        // 多选按钮组状态改变事件
        handleCheckedPlatformsChange(value) {
            let checkedCount = value.length;
            this.platformAll = checkedCount === 2;
        },

        // 获取分类列表
        getCategory() {
            // 获取类别
            this.my_request('supplier/market/category').then(res => {
                // console.log(res, '获取类别res');
                let { code, data } = res.data
                if (200 === code) {
                    this.categoryList = data
                }
            })
            // 获取品牌
            this.my_request('/supplier/market/brand').then(res => {
                // console.log(res, '获取品牌res');
                let { code, data } = res.data
                if (200 === code) {
                    this.brandList = data.map(item => {
                        // 创建一个新对象，只保留 id 和 label 属性
                        const option = {
                            value: item.id,
                            label: item.name,
                        };
                        return option
                    })
                    // console.log(this.brandList, 'this.brandList');
                }
            })
        },
        /**
         * 使用递归函数， 处理分类列表的数据格式为options格式
         * @param {*} data 分类列表
         */
        categoryListToOptions(data) {
            return data && data.map(item => {
                // 创建一个新对象，只保留 id 和 label 属性
                const option = {
                    value: item.id,
                    label: item.category_name,
                };

                // 如果当前分类有子分类，则使用递归将子分类也转换为 options 格式
                if (Array.isArray(item.child) && item.child.length > 0) {
                    option.children = this.categoryListToOptions(item.child);
                }

                return option;
            });
        },
    }
}
</script>


<style lang="scss" scoped>
.addGoods {
    margin: 10px;
    width: calc(100% - 60px);
    height: calc(100% - 170px);
    background-color: white;
    padding: 20px;
    overflow: auto;

    .addGoods_form {
        width: 700px;

        // background-color: aquamarine;
        // width: 100%;
        // height: 100%;
        .formCheckbox {
            display: flex;

            .el-checkbox {
                margin-right: 20px;
            }
        }

        .el-form-item {
            margin-bottom: 5px;
        }
    }

    .addGoods_Bottom {
        margin-top: 20px;
        display: flex;
        justify-content: end;
        margin-right: 100px;
    }
}

/* 隐藏滚动条 */
.addGoods::-webkit-scrollbar {
    width: 0;
    /* 设置滚动条宽度为0em */
}


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 68px;
    height: 68px;
    line-height: 68px;
    text-align: center;
    border: 1px dashed #d9d9d9;
}

.avatar {
    width: 68px;
    height: 68px;
    display: block;
}
</style>
